package com.core.utils;

import java.util.ArrayList;
import java.util.List;

import com.core.entity.Condition;
import com.core.entity.Query;
import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.TableMapping;

@SuppressWarnings("rawtypes")
public class ConditionDb extends Db {
	
	private final static List<Condition> emptyConditions = new ArrayList<Condition>();
	
	public static List<Record> find(Class<? extends Model> modelClass , List<Condition> conditions){
		String tableName = TableMapping.me().getTable(modelClass).getName();
		Query query = SqlKit.buildQuery(tableName, conditions);
		return find("select * "+query.getSql(), query.getParamList().toArray());
	}
	
	public static List<Record> find(Class<? extends Model> modelClass , Condition condition){
		List<Condition> conditions = null;
		if (condition != null) {
			conditions = Lists.newArrayListWithExpectedSize(1);
			conditions.add(condition);
		}
		return find(modelClass, conditions);
	}
	
	public static List<Record> findAll(Class<? extends Model> modelClass){
		return find(modelClass, emptyConditions);
	}
	
	public static boolean isRepeat(Class<? extends Model> modelClass,String coloumnName,String coloumnValue){
		Condition condition = Condition.parseCondition(coloumnName+"_"+"string"+"_eq");
		condition.setValue(coloumnValue);
		List<Record> list = find(modelClass, condition);
		if(list.isEmpty()){
			return false;
		}
		return true;
	}
	
	public static int delete(Class<? extends Model> modelClass, Condition condition){
		List<Condition> conditions = Lists.newArrayList();
		conditions.add(condition);
		return delete(modelClass, conditions);
	}
	
	public static int delete(Class<? extends Model> modelClass, List<Condition> conditions){
		String tableName = TableMapping.me().getTable(modelClass).getName();
		Query query = SqlKit.buildQuery(tableName, conditions);
		String sql = "delete "+query.getSql() ;
		return update(sql, query.getParamList().toArray());
	}
	
}
